﻿using GoogleMobileAds.Api;
using System;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GoogleAdMobController : MonoBehaviour
{
    public static GoogleAdMobController instance;

    public GameObject adNotLoadNotic;
    //public Text log;

    private BannerView bannerView;
    private bool bannerReload;
    private RewardBasedVideoAd rewardBasedVideo;
    private bool rewardReload;

    public string bannerAndID = "ca-app-pub-3940256099942544/6300978111";
    //public string bannerIosId = "ca-app-pub-3940256099942544/2934735716";
    public string rewardAndID = "ca-app-pub-3940256099942544/5224354917";

    //真实广告ID
    //public string bannerAndID = "ca-app-pub-1827848971928864/2666619921";
    //public string rewardAndID = "ca-app-pub-1827848971928864/3096938720";

    private bool rewardBool;



    private void Awake()
    {
        if (instance != null)
        {
            Destroy(this);
        }
        instance = this;
    }

    void Start()
    {
        string appId = "unexpected_platform";
#if UNITY_ANDROID || UNITY_EDTIOR
        appId = "ca-app-pub-1827848971928864~3347138598";
#elif UNITY_IPHONE
         appId = "ca-app-pub-3940256099942544~1458002511";
#endif
        //初始化 Google Mobile Ads SDK.
        MobileAds.Initialize(appId);


        // Get singleton reward based video ad reference.
        //激励广告实例化
        this.rewardBasedVideo = RewardBasedVideoAd.Instance;

        RequestBanner();
        RequestReward();
    }

    /// <summary>
    /// 请求Banner广告
    /// </summary>
    public void RequestBanner()
    {
        string adUnitId = "unexpected_platform";
#if UNITY_ANDROID
        adUnitId = bannerAndID;
#elif UNITY_IPHONE
        adUnitId = bannerIosID;
#endif

        //实例化Banner
        // adUnitId - BannerView加载广告单元的ID
        // AdSize - Banner广告的相关尺寸（如果尺寸太大，可能Banner不会显示）
        // AdPosition - banner广告显示的位置（枚举类型）
        bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Bottom);

        // 广告加载完成后调用
        bannerView.OnAdLoaded += HandleOnAdLoadedBanner;
        // 广告加载失败时调用
        bannerView.OnAdFailedToLoad += HandleOnAdFailedToLoadBanner;
        //当广告被点击时调用（记录 跟踪用户点击率的好地方）
        bannerView.OnAdOpening += HandleOnAdOpenedBanner;
        // 当玩家观看完广告后，点击返回游戏时调用（可以使用此方法恢复暂停的活动，或执行任何其他必要的操作，以做好互动准备。）
        bannerView.OnAdClosed += HandleOnAdClosedBanner;
        // 当玩家点击打开了其他应用程序（如Google Play）时调用（也就是点击广告跳转出去当前游戏了）
        bannerView.OnAdLeavingApplication += HandleOnAdLeavingApplicationBanner;

        // 创建一个请求
        AdRequest request = new AdRequest.Builder().Build();

        //通过请求去加载Banner. 
        bannerView.LoadAd(request);

    }
    //显示Banner
    public void ShowBanner()
    {
        bannerView.Show();
    }
    //隐藏Banner
    public void HideBanner()
    {
        bannerView.Hide();
    }


    /// <summary>
    /// 请求激励广告
    /// </summary>
    public void RequestReward()
    {
#if UNITY_ANDROID
        string adUnitId = rewardAndID;
#elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/1712485313";
#else
            string adUnitId = "unexpected_platform";
#endif

        // Called when an ad request has successfully loaded.
        rewardBasedVideo.OnAdLoaded += HandleRewardBasedVideoLoaded;
        // Called when an ad request failed to load.
        rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoFailedToLoad;
        // Called when an ad is shown.
        rewardBasedVideo.OnAdOpening += HandleRewardBasedVideoOpened;
        // Called when the ad starts to play.
        rewardBasedVideo.OnAdStarted += HandleRewardBasedVideoStarted;
        // Called when the user should be rewarded for watching a video.
        rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
        // Called when the ad is closed.
        rewardBasedVideo.OnAdClosed += HandleRewardBasedVideoClosed;
        // Called when the ad click caused the user to leave the application.
        rewardBasedVideo.OnAdLeavingApplication += HandleRewardBasedVideoLeftApplication;

        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the rewarded video ad with the request.
        this.rewardBasedVideo.LoadAd(request, adUnitId);
    }
    //显示激励广告
    public void ShowRewardAd()
    {
        if (rewardBasedVideo.IsLoaded())
        {
            Debug.Log("load");
            rewardBasedVideo.Show();
        }
        else
        {
            Debug.Log("load fail");
            StartCoroutine(NoticShow());
        }
    }
   

    #region Banner广告的回调函数
    public void HandleOnAdLoadedBanner(object sender, EventArgs args)
    {
        print("HandleAdLoaded event received");
        StopCoroutine(RequestBannerAgain());
    }

    public void HandleOnAdFailedToLoadBanner(object sender, AdFailedToLoadEventArgs args)
    {
        print("HandleFailedToReceiveAd event received with message: " + args.Message);
        if (!bannerReload)
        {
            bannerReload = true;
            StartCoroutine(RequestBannerAgain());
        }
        else
        {
            bannerReload = false;
        }
    }

    public void HandleOnAdOpenedBanner(object sender, EventArgs args)
    {
        print("HandleAdOpened event received");
    }

    public void HandleOnAdClosedBanner(object sender, EventArgs args)
    {
        print("HandleAdClosed event received");
        bannerView.Destroy();
        //RequestBanner();
        StartCoroutine(RequestBannerAgain());
    }

    public void HandleOnAdLeavingApplicationBanner(object sender, EventArgs args)
    {
        print("HandleAdLeavingApplication event received");
    }
    #endregion


    #region 激励广告的回调
    public void HandleRewardBasedVideoLoaded(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleRewardBasedVideoLoaded event received");
        StopCoroutine(RequestRewardAgain());
    }

    public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        MonoBehaviour.print(
            "HandleRewardBasedVideoFailedToLoad event received with message: "
                             + args.Message);

        if (!rewardReload)
        {
            rewardReload = true;
            StartCoroutine(RequestRewardAgain());
        }
        else
        {
            rewardReload = false;
        }
    }

    public void HandleRewardBasedVideoOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleRewardBasedVideoOpened event received");
    }

    public void HandleRewardBasedVideoStarted(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleRewardBasedVideoStarted event received");
    }

    /// <summary>
    /// 广告关闭时执行
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleRewardBasedVideoClosed event received");
        
        RequestReward();

        if (rewardBool)
        {
            GameObject panel_LuckyDraw = GameObject.Find("Panel_LuckyDraw(Clone)");
            panel_LuckyDraw.GetComponent<Panel_LuckyDraw>().LuckyDrawRotate();
            //log.text += "luckyDraw——knock";
            rewardBool = false;
        }
        
    }

    /// <summary>
    /// 激励广告的奖励机制
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    public void HandleRewardBasedVideoRewarded(object sender, Reward args)
    {
        string type = args.Type;
        double amount = args.Amount;
        print(
            "HandleRewardBasedVideoRewarded event received for "
                        + amount.ToString() + " " + type);

        if (User.instance.moneyBool)
        {
            User.instance.ChangeMoney(500);
            User.instance.moneyBool = false;
        }

        if (User.instance.skinBool)
        {
            User.instance.skinOnSwitch.WatchForSkin();
            User.instance.skinBool = false;
        }

        if (User.instance.luckyBool)
        {
            rewardBool = true;
            User.instance.luckyBool = false;
        }

        if (User.instance.skipBool)
        {
            User.instance.ThroughLevel();
            UIManager.Instance.PopPanel();
            GameControl.instance.GameBegin();
            User.instance.skipBool = false;
        }
    }

    public void HandleRewardBasedVideoLeftApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleRewardBasedVideoLeftApplication event received");
    }

    #endregion

    public IEnumerator RequestBannerAgain()
    {
        yield return new WaitForSeconds(2f);
        RequestBanner();
    }

    public IEnumerator RequestRewardAgain()
    {
        yield return new WaitForSeconds(2f);
        RequestReward();
    }


    /// <summary>
    /// 广告未加载提示
    /// </summary>
    /// <returns></returns>
    public IEnumerator NoticShow()
    {
        adNotLoadNotic.gameObject.SetActive(true);

        yield return new WaitForSeconds(0.8f);
        adNotLoadNotic.gameObject.SetActive(false);
    }

}